package com.pds.web.opsOrganization.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.pds.common.core.domain.entity.SysDept;
import com.pds.common.core.domain.entity.SysRole;
import com.pds.common.core.domain.entity.SysUser;
import com.pds.common.utils.DateUtils;
import com.pds.common.utils.SecurityUtils;
import com.pds.common.utils.StringUtils;
import com.pds.system.domain.FileUpload;
import com.pds.system.domain.SysUserRole;
import com.pds.system.mapper.*;
import com.pds.utils.FileUtil;
import com.pds.utils.IdCardUtil;
import com.pds.web.company.excel.CompanyContactExcel;
import com.pds.web.opsOrganization.domain.OpsOrganizationInfo;
import com.pds.web.opsOrganization.mapper.OpsOrganizationMapper;
import com.pds.web.opsOrganization.service.IOpsOrganizationService;
import com.pds.web.opsOrganization.service.IOpsOrganizationUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class OpsOrganizationUserServiceImpl implements IOpsOrganizationUserService {

    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private SysRoleMapper sysRoleMapper;
    @Autowired
    private OpsOrganizationMapper opsOrganizationMapper;
    @Autowired
    private SysUserRoleMapper userRoleMapper;
    @Autowired
    private IOpsOrganizationService opsOrganizationService;
    @Autowired
    private FileUploadMapper fileUploadMapper;

    /**管理员角色名称*/
    private static final String OPS_ADMIN_ROLE_NAME = "opsAdmin";
    /**普通用户角色名称*/
    private static final String OPS_USER_ROLE_NAME = "opsCommon";


    /**
     * 运维机构新增用户
     *
     * @param map - userName 用户名
     *            - phone 手机号
     *            - roleId 角色id
     *            - idCard 身份证号
     *            - commitmentFileId 守法诚信运维承诺书id
     *            - certificateFileId 运维业务考试证书id
     * @return
     * @throws Exception
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void addUser(Map<String,String> map) throws Exception {
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        String userName = map.get("userName");
        String phone = map.get("phone");
        String roleId = String.valueOf(map.get("roleId"));
        String remark = map.get("remark");
        if(StringUtils.isEmpty(userName)) {
            throw new Exception("姓名不能为空");
        }
        if(StringUtils.isEmpty(phone)) {
            throw new Exception("手机号不能为空");
        }
        if(ObjectUtil.isEmpty(map.get("idCard"))) {
            throw new Exception("身份证号不能为空");
        }
        String idCard = String.valueOf(map.get("idCard"));
        if(!IdCardUtil.check(idCard)){
            throw new Exception("身份证号不正确，请核实");
        }
        //判断用户表是否存在同手机号
        SysUser user = sysUserMapper.selectUserByUserName(phone);
        if (user != null) {
            throw new Exception("新增失败，已存在相同手机号账户，请核实");
        }
        OpsOrganizationInfo info = new OpsOrganizationInfo();
        info.setContactName(userName);
        info.setContactPhone(phone);
        info.setRemark(remark);
        SysDept dept = sysUser.getDept();
        dept.setCreateBy(sysUser.getNickName());
        SysUser newUser = opsOrganizationService.addSysUser(info, dept, OPS_USER_ROLE_NAME, roleId);
        map.put("userId",newUser.getUserId().toString());
        //保存用户身份证、守法诚信运维承诺书id、运维业务考试证书id
        opsOrganizationMapper.saveUserInfo(map);
    }



    /**
     * 修改用户
     *
     * @param map
     */
    @Override
    public void updateUser(Map map) throws Exception {
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        String roleId = map.get("roleId")!=null?String.valueOf(map.get("roleId")):null;
        String userId = String.valueOf(map.get("userId"));
        String phone = map.get("phone")!=null?String.valueOf(map.get("phone")):null;
        String status = map.get("status")!=null?String.valueOf(map.get("status")):null;

        String idCard = String.valueOf(map.get("idCard"));
        if(ObjectUtil.isNotEmpty(map.get("idCard")) && !IdCardUtil.check(idCard)){
            throw new Exception("身份证号不正确，请核实");
        }

        //判断用户表是否存在同手机号
        SysUser existUser = sysUserMapper.selectUserByUserName(phone);
        if (existUser != null && !userId.equals(existUser.getUserId().toString())) {
            throw new Exception("修改失败，已存在相同手机号账户，请核实");
        }

        //判断本次修改是不是去掉了管理员权限，至于要有一个管理员账号
        List<Map> roles = sysRoleMapper.getAdminRoleByRoleKey(sysUser.getDeptId(), OPS_ADMIN_ROLE_NAME);
        if(roles.size() == 1){
            Map role = roles.get(0);
            //查看是否是当前修改的
            if(userId.equals(role.get("userId").toString())){
                if(StringUtils.isNotEmpty(status) && !"0".equals(status)){
                    throw new Exception("至少需要有一个管理员");
                }
                if(!roleId.contains(role.get("roleId").toString())){
                    throw new Exception("至少需要有一个管理员");
                }
            }
        }
        SysUser user = new SysUser();
        user.setUserId(Long.parseLong(userId));
        if(ObjectUtil.isNotEmpty(map.get("userName"))) {
            user.setNickName(String.valueOf(map.get("userName")));
        }
        if(ObjectUtil.isNotEmpty(map.get("phone"))) {
            user.setUserName(String.valueOf(map.get("phone")));
        }
        user.setPhonenumber(phone);
        if(ObjectUtil.isNotEmpty(map.get("remark"))) {
            user.setRemark(String.valueOf(map.get("remark")));
        }
        user.setUpdateBy(sysUser.getNickName());
        user.setStatus(status);
        sysUserMapper.updateUser(user);
        if(ObjectUtil.isNotEmpty(map.get("roleId"))) {
            //删除角色，重新保存
            userRoleMapper.deleteUserRoleByUserId(Long.parseLong(userId));
            // 新增用户与角色管理
            opsOrganizationService.addRoles(Long.parseLong(userId), roleId);
        }
        //更新用户其他信息
        if(ObjectUtil.isNotEmpty(map.get("idCard"))||
                ObjectUtil.isNotEmpty(map.get("commitmentFileId"))||
                ObjectUtil.isNotEmpty(map.get("certificateFileId"))) {
            opsOrganizationMapper.updateUserInfo(map);
        }
    }

    /**
     * 批量导入人员
     *
     * @param list
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Integer addUserBatch(List<CompanyContactExcel> list) throws Exception {
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        SysDept dept = sysUser.getDept();
        dept.setCreateBy(sysUser.getNickName());
        for (int i = 0; i < list.size(); i++) {
            CompanyContactExcel data = list.get(i);
            SysUser user = sysUserMapper.selectUserByUserName(data.getPhone());
            if (user != null && "0".equals(user.getDelFlag()))  {
                throw new Exception("导入失败，"+data.getPhone()+"已存在相同手机号账户，请核实");
            }
            OpsOrganizationInfo info = new OpsOrganizationInfo();
            info.setContactName(data.getName());
            info.setContactPhone(data.getPhone());
            info.setRemark(data.getRemark());
            opsOrganizationService.addSysUser(info, dept,OPS_USER_ROLE_NAME,null);
        }
        return list.size();
    }

    /**
     * 查询运维机构用户列表
     * map
     *  - opsId 环保局查询时需要传入id
     *  - userName 姓名
     *  - phone 电话
     *  - idCard 身份证号码
     * @return
     */
    @Override
    public List<Map> getOrganizationUserList(Map map) throws Exception {
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        SysDept dept = sysUser.getDept();
        if("3".equals(String.valueOf(dept.getType()))){
            map.put("opsId",dept.getDeptId());
        }
        List<Map> list = opsOrganizationMapper.getOrganizationUserList(map);
        list.forEach(item ->{
            //查询运维工程师管辖的站房
            Map station = opsOrganizationMapper.selectStationByUserId(item.get("userId"));
            if(station!=null) {
                item.putAll(station);
            }
        });
        return list;
    }

    /**
     * 查询运维机构用户详细
     * userId 用户id
     *
     * @param userId
     * @return
     */
    @Override
    public Map getUserInfo(Long userId) {
        Map map = opsOrganizationMapper.getUserInfo(userId);
        if(ObjectUtil.isNull(map)){
            return null;
        }
        map.put("commitmentFile",null);
        map.put("certificateFile",null);
        //查询附件信息
        if(ObjectUtil.isNotEmpty(map.get("commitmentFileId"))){
            FileUpload fileUpload = fileUploadMapper.selectFileUploadById(String.valueOf(map.get("commitmentFileId")));
            map.put("commitmentFile", FileUtil.structureFile(fileUpload));
        }
        if(ObjectUtil.isNotEmpty(map.get("certificateFileId"))){
            FileUpload fileUpload = fileUploadMapper.selectFileUploadById(String.valueOf(map.get("certificateFileId")));
            map.put("certificateFile",FileUtil.structureFile(fileUpload));
        }
        return map;
    }
}
